package com.cloudauth.core.intercepter;


import com.alibaba.fastjson.JSON;
import com.cloudauth.core.util.UserPermissionUtil;
import com.cloudauth.core.vo.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserContextInterceptor  extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        User user = getUser(request);
        UserPermissionUtil.permission(user);

        if (!UserPermissionUtil.verify(user,request)){
            response.setHeader("Content-type","application/json");

            String responseStr = JSON.toJSONString("no permission access service,please check");

            response.getWriter().write(responseStr);
            response.getWriter().flush();
            response.getWriter().close();

            throw new PermissionException("no permission access service,please check");
        }
        UserContextHolder.set(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.shutdown();
    }

    private User getUser(HttpServletRequest request){
        String userid = request.getHeader("x-user-id");
        String username = request.getHeader("x-user-name");
        User user = new User();
        user.setUserId(userid);
        user.setUserName(username);
        return user;
    }


    static class PermissionException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        public PermissionException(String msg) {
            super(msg);
        }
    }
}
